package com.gbb.common.utils;

import java.security.MessageDigest;

import android.text.TextUtils;

/**
 * MD5 加密
 *
 * @author liudongsheng
 * @version v3.0
 * @since 2012-10-10下午07:07:16
 */
public class Md5Util {

    /**
     * 对字符串加密
     *
     * @param str String
     * @return 加密后的字符串
     */
    public static String getMD5Str(String str){
        if(TextUtils.isEmpty(str)) {
            return "";
        }
        MessageDigest messageDigest = null;
        StringBuilder md5StrBuff = new StringBuilder();

        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
            byte[] byteArray = messageDigest.digest();


            for(byte aByteArray : byteArray) {
                if(Integer.toHexString(0xFF&aByteArray).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF&aByteArray));
                } else {
                    md5StrBuff.append(Integer.toHexString(0xFF&aByteArray));
                }
            }

        } catch(Exception e) {
            e.printStackTrace();
        }

        return md5StrBuff.toString();
    }

    /**
     * 加密对象
     *
     * @param objects 对象数组
     * @return 加密后的串
     */
    public static String getMD5String(Object... objects){
        StringBuilder sb = new StringBuilder();
        for(Object obj : objects) {
            if(obj != null) {
                sb.append(obj.toString());
            }
        }
        return getMD5Str(sb.toString());
    }

}
